// home主页用到的tab标签页相关数据
import { defineStore } from "pinia";
import pageFiles from "@/utils/pageFiles.ts";

export const homeStore = defineStore("homeStore", {
  state: (): homeState => ({
    homeTabs: [], // 打开的 home 页 tab 列表
    checkedTab: {
      tabName: "首页&joint&Desktop",
      compontentName: pageFiles.Desktop,
      params: {},
    },
    dicts: {},
  }),
  actions: {
    changeHomeTabs(params: TabItem[]) {
      // console.log('piniaAction:homeTabs接收的参数=>', params)
      this.homeTabs = params;
    },
    changeCheckedTab(params: CheckedTab) {
      // console.log('piniaAction:checkedTab接收的参数=>', params)
      this.checkedTab = params;
    },
    openTabPage(
      title: string,
      componentName: string,
      params: Record<string, any>
    ) {
      if (componentName === "Desktop") {
        title = "首页";
      }
      console.log("打开tab页面: ", {
        title,
        componentName,
        params,
      });
      const component = pageFiles[componentName] || pageFiles.NotFound;
      // tab列表里是否已经存在
      const index = this.homeTabs.findIndex((item) => {
        const pathSegments = item.menuPath.split("/");
        return (
          item.menuName + "&joint&" + pathSegments[pathSegments.length - 1] ===
          title + "&joint&" + componentName
        );
      });
      
      const hasListLog = index !== -1 ? true : null;
      if (hasListLog || componentName === "Desktop") {
        this.checkedTab.compontentName = component;
        this.checkedTab.tabName = title + "&joint&" + componentName;
        this.checkedTab.params = params;
        this.homeTabs[index].params = params;
      } else {
        this.checkedTab.compontentName = component;
        this.checkedTab.tabName = title + "&joint&" + componentName;
        this.checkedTab.params = params;
        this.homeTabs.push({
          menuId: Math.floor(Math.random() * 100),
          menuName: title,
          menuPath: componentName,
          component: component,
          params: params
        });
      }
    },
    changeDicts(params: Record<string, any>) {
      console.log("piniaAction:changeDicts接收的参数=>", params);
      this.dicts = params;
    },
  },
});
